import { Injectable, OnModuleInit } from '@nestjs/common';
import * as utils from '@utils/utils';
import config from '@config/constants';

import swaggerParserMock = require('swagger-parser-mock');
const specs = swaggerParserMock(config.SWAGGER_BASE_URL);
@Injectable()
export class AppService implements OnModuleInit {
  private data: any;
  async onModuleInit(): Promise<void> {
    const docs = await this.getAll();
    const methods = {
      get: true,
      post: true,
      put: true,
      delete: true,
      patch: true,
    };
    let num = 0;
    const result = {};
    for (const o of Object.keys(docs.paths)) {
      for (const i of Object.keys(docs.paths[o])) {
        if (methods[i]) {
          const example = docs.paths[o][i].responses['200'].example
            ? docs.paths[o][i].responses['200'].example
            : '{}';

          // API_PREFIX 不允许以 / 结尾
          const data = {
            url: `${config.API_PREFIX || docs.basePath}${o}`,
            example: JSON.parse(example),
            method: i.toUpperCase(),
          };
          result[`${data.method}-${data.url}`] = data;
          num = num + 1;
        }
      }
    }
    this.data = utils.genMockData(result);
  }
  getData(method: string, url: string): any {
    let data;
    const api = this.data[`${method}-${url}`];
    if (api) {
      data = api.data;
    }

    return data !== undefined ? data : {};
  }
  async getAll(): Promise<any> {
    return await specs;
  }
}
